package com.jy.service.impl;

import com.jy.dao.AppBaseDao;
import com.jy.model.TaskLeave;
import com.jy.service.AppBaseService;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.impl.identity.Authentication;
import org.activiti.engine.impl.persistence.entity.ProcessDefinitionEntity;
import org.activiti.engine.impl.pvm.PvmTransition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Comment;
import org.activiti.engine.task.Task;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Component
public class AppBaseSerivceImpl implements AppBaseService{
	@Resource
	RuntimeService runtimeService;
	@Resource
	TaskService taskService;
	@Resource
	RepositoryService repositoryService;
	@Resource
	HistoryService historyService;
	@Resource
	AppBaseDao appBaseDao;
	/**
	 * 系统用户提交申请方法
	 * @param assigneeKey 提交人Key 流程图中assignee变量
	 * @param assigneeValue 提交人姓名 一般为系统当前登录用户
	 * @param processInstanceKey 流程实例Key，在自己构建的流程图中的Id
 	 * @return ProcessInstance 流程实例对象，用来获取当前流程实例的相关信息
	 */
	public ProcessInstance startProcessInstance(String assigneeKey,
			String assigneeValue, String processInstanceKey,String bussinessId) {
		// TODO Auto-generated method stub
		Map<String,Object> variables=new HashMap<String,Object>();
		variables.put(assigneeKey,assigneeValue);
		String objId=bussinessId;//key+"."+业务ID
		variables.put("objId", objId);
		return runtimeService.startProcessInstanceByKey(processInstanceKey, objId,variables);
	}
	public Task getTask(String processInstanceId) {
		// TODO Auto-generated method stub
		return taskService.createTaskQuery().processInstanceId(processInstanceId).singleResult();
	}
	
	public ActivityImpl getActivityImpl(String processInstanceId) {
		Task tk=getTask(processInstanceId);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        String currentActivitiId = pi.getActivityId();
        // 2. 获取到流程定义
        ProcessDefinitionEntity pd = (ProcessDefinitionEntity) repositoryService.getProcessDefinition(tk.getProcessDefinitionId());
        // 3. 使用流程定义通过currentActivitiId得到活动对象
        ActivityImpl activity =  pd.findActivity(currentActivitiId);
        // 4. 获取活动的坐标
        return activity;
	}

	public List<TaskLeave> getTask(Integer start, Integer length, String assignee) {
		// TODO Auto-generated method stub
		System.out.println(assignee+"起始页数："+start+"====该页条数："+length);
		//taskService.createTaskQuery().taskAssignee(assignee).listPage(start, length);
		 
		return appBaseDao.getTaskLeave(start,length,assignee);
				
	}
	public long getTaskCount(String assignee) {
		// TODO Auto-generated method stub
		return taskService.createTaskQuery().taskAssignee(assignee).count();
	}
	public List<String> getTaskPvm(String taskid) {
		// TODO Auto-generated method stub
		List<String> list=new ArrayList<String>();
		Task task=taskService.createTaskQuery().taskId(taskid).singleResult();
		//获取流程定义id
		String processDefinitionId=task.getProcessDefinitionId();
		//获取ProcessDefinitionEntity
		ProcessDefinitionEntity processDefinitionEntity=(ProcessDefinitionEntity)repositoryService.getProcessDefinition(processDefinitionId);
		ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(task.getProcessInstanceId()).singleResult();
		ActivityImpl activityImpl= processDefinitionEntity.findActivity(processInstance.getActivityId());
		List<PvmTransition> pvmTransitionList=activityImpl.getOutgoingTransitions();
		if(pvmTransitionList!=null&&pvmTransitionList.size()>0){
			for(PvmTransition pvmTransition:pvmTransitionList){
				String name=(String) pvmTransition.getProperty("name");
				if(!"".equals(name)&&name!=null){
					list.add(name);
				}else{
				}
			}
		}
		return list;
	}
	//刘花专用
	public ProcessInstance applyComplete(String pocessId,Map<String,Object> variables) {
		// TODO Auto-generated method stub
		Task tk=getTask(pocessId);
		/*Map<String,Object> variables=new HashMap<String,Object>();
		variables.put(assigneeKey,assigneeValue);*/
		taskService.complete(tk.getId(),variables);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
				.processInstanceId(pocessId).singleResult();
 		if(pi==null){
			System.out.println("流程结束啦！");
		}else{
			System.out.println("流程还没有结束哦");
		}
		return pi;
	}
	
	public ProcessInstance applyComplete(String pocessId, Map<String,Object> variables
			, String commons,String tjuser,String btnName) {
			
				Task tk=getTask(pocessId);
				Authentication.setAuthenticatedUserId(tjuser);
				taskService.addComment(tk.getId(), pocessId, commons);
				//taskService.getProcessInstanceComments(pocessId);
/*				Map<String,Object> variables=new HashMap<String,Object>();
				variables.put("message",btnName);
				variables.put(assigneeKey,assigneeValue);
*/				taskService.complete(tk.getId(),variables);
				ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
						.processInstanceId(pocessId).singleResult();
				
				if(pi==null){
					System.out.println("流程结束啦！");
				}else{
					System.out.println("流程还没有结束哦");
				}
				return pi;
	}
	public ProcessInstance applyComplete(String pocessId,String assigneeKey,
			String assigneeValue) {
		// TODO Auto-generated method stub
		Task tk=getTask(pocessId);
		Map<String,Object> variables=new HashMap<String,Object>();
		variables.put(assigneeKey,assigneeValue);
		taskService.complete(tk.getId(),variables);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
				.processInstanceId(pocessId).singleResult();
		if(pi==null){
			System.out.println("流程结束啦！");
		}else{
			System.out.println("流程还没有结束哦");
		}
		return pi;
	}
	public List<Comment> getCommon(String pocessId) {
		// TODO Auto-generated method stub
		Task tk=getTask(pocessId);
		return taskService.getProcessInstanceComments(pocessId);
	}
	//获取流程历史批注
	public List<Comment> getHistoryComment(String pocessId) {
		
		HistoricProcessInstance his = historyService.createHistoricProcessInstanceQuery()
			.processInstanceBusinessKey(pocessId)
			.singleResult();
		
		
		String processId = his.getId();
		System.out.println("processId00000-------"+processId);
		
		List<Comment> list = taskService.getProcessInstanceComments(pocessId);
		return list;
	}
	public ProcessDefinition getTaskImage(String pocessId) {
		// TODO Auto-generated method stub
		Task tk=getTask(pocessId);
		return repositoryService.createProcessDefinitionQuery().processDefinitionId(tk.getProcessDefinitionId()).singleResult();
	}
	public InputStream getImageStream(String deploymentId, String imageName) {
		// TODO Auto-generated method stub
		return repositoryService.getResourceAsStream(deploymentId, imageName);
	}
	public void deleteProcessInstance(String processId, String reason) {
		// TODO Auto-generated method stub
		runtimeService.deleteProcessInstance(processId, reason);
	}
	public List<HistoricTaskInstance> findHistoryTask(String processId) {
		// TODO Auto-generated method stub
		List<HistoricTaskInstance> list = historyService//与历史数据（历史表）相关的Service  
                .createHistoricTaskInstanceQuery()//创建历史任务实例查询  
                .processInstanceId(processId)//  
                .orderByHistoricTaskInstanceStartTime().asc()  
                .list(); 
		return list;
	}
	public HistoricTaskInstance historyImage(String processId){
		Task tk=getTask(processId);
		
		return null;
	}
	public List<HistoricTaskInstance> findHistoryAssigneeTask(String assignee) {
		// TODO Auto-generated method stub
		 List<HistoricTaskInstance> list=historyService // 历史任务Service  
		            .createHistoricTaskInstanceQuery() // 创建历史任务实例查询  
		            .taskAssignee(assignee) // 指定办理人  
		            //.finished() // 查询已经完成的任务    
		            .list();
		 return list;
	}
	public ProcessInstance applyComplete(String pocessId,
			Map<String, Object> variables, String tjuser, String btnName) {
		
		Task tk=getTask(pocessId);
		Authentication.setAuthenticatedUserId(tjuser);
		taskService.addComment(tk.getId(), pocessId, "");
		//taskService.getProcessInstanceComments(pocessId);
/*				Map<String,Object> variables=new HashMap<String,Object>();
		variables.put("message",btnName);
		variables.put(assigneeKey,assigneeValue);
*/				taskService.complete(tk.getId(),variables);
		ProcessInstance pi = runtimeService.createProcessInstanceQuery()//
				.processInstanceId(pocessId).singleResult();
		
		if(pi==null){
			System.out.println("流程结束啦！");
		}else{
			System.out.println("流程还没有结束哦");
		}
		return pi;
	}
}
